export function getQueryObject() {
    var url = window.location.href
    const search = url.substring(url.lastIndexOf('?') + 1)
    const obj = {}
    const reg = /([^?&=]+)=([^?&=]*)/g
    search.replace(reg, (rs, $1, $2) => {
        const name = decodeURIComponent($1)
        let val = decodeURIComponent($2)
        val = String(val)
        obj[name] = val
        return rs
    })
    return obj
}

export function isWeChat() {
    let ua = window.navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == "micromessenger"; // 判定为true则是微信浏览器，false则不是
}

export function checkNullObj(obj) {
    if (Object.keys(obj).length === 0 || !obj) {
        return false
    }
    return true
}

/**
 * 10000 => "10,000"
 * @param {number} num
 */
export function toThousandFilter(num) {
    return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string')) {
            if ((/^[0-9]+$/.test(time))) {
                // support "1548221490638"
                time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

export function getUnixTime(dateStr){
    var newstr = dateStr.replace(/-/g,'/');
    var date =  new Date(newstr);
    var time_str = date.getTime().toString();
    return time_str
}

/**
 * 判读是否为整数
 * @param num
 * @returns {boolean}
 */
export function isInteger(num) {
    if (!isNaN(num) && num % 1 === 0) {
        return true
    } else {
        return false
    }
}

export function keepTwoDecimalFull(num) {
    var result = parseFloat(num);
      if (isNaN(result)) {
         return false;
     }
     result = Math.round(num * 100) / 100;
      var s_x = result.toString(); //将数字转换为字符串
      var pos_decimal = s_x.indexOf('.'); //小数点的索引值
      // 当整数时，pos_decimal=-1 自动补0
     if (pos_decimal < 0) {
          pos_decimal = s_x.length;
          s_x += '.';
      }
      // 当数字的长度< 小数点索引+2时，补0
    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }
    return s_x;
}

export function throttle(fn, threshold) {
    // 记录上次执行的时间
    var last
    // 定时器
    var timer
    // 默认间隔为 250ms
    threshold || (threshold = 250)
    // 返回的函数，每过 threshold 毫秒就执行一次 fn 函数
    return function() {
        // 保存函数调用时的上下文和参数，传递给 fn
        var context = this
        var args = arguments
        var now = +new Date()
        // 如果距离上次执行 fn 函数的时间小于 threshold，那么就放弃
        // 执行 fn，并重新计时
        if (last && now < last + threshold) {
            clearTimeout(timer)
            // 保证在当前时间区间结束后，再执行一次 fn
            timer = setTimeout(function() {
                last = now
                fn.apply(context, args)
            }, threshold)
            // 在时间区间的最开始和到达指定间隔的时候执行一次 fn
        } else {
            last = now
            fn.apply(context, args)
        }
    }
}

/**
 * 隐秘文本数据
 * @param str          字符串
 * @param start        前面保留字符位数
 * @param end          后面保留字符位数
 * @returns {string|*}
 */
export function secretText(str, start=3, end=-3, replace='***') {
    if (!str) {
        return str
    }
    var sub1 = str.slice(0, start)
    var sub2 = str.slice(end)
    return sub1 + replace +sub2
}
